import { ref,onActivated,onDeactivated,onMounted,onUnmounted } from "vue"

export default function getScroll(elRef) {
    let el = window

    let scrollTop = ref(0)
    let clientHeight = ref(0)
    let scrollHeight = ref(0)
    let isBottom = ref(false)

    const fn = () => {
        if (el === window) {
            el = document
            scrollTop.value = el.documentElement.scrollTop
            clientHeight.value = el.documentElement.clientHeight
            scrollHeight.value = el.documentElement.scrollHeight
        } else {
            scrollTop.value = el.scrollTop
            clientHeight.value = el.clientHeight
            scrollHeight.value = el.scrollHeight
        }
        if (scrollTop.value + clientHeight.value > scrollHeight.value - 2) {
            isBottom.value = true
            console.log("滚动到底部了");
        } else {
            isBottom.value = false
        }
    }

    onActivated(() => {
        if (elRef) el = elRef.value
        console.log("添加了滚动事件");
        el.addEventListener("scroll",fn)
    })
    onDeactivated(() => {
        console.log("移除s了滚动事件");
        el.removeEventListener("scroll",fn)
    })
    onMounted(() => {
        if (elRef) el = elRef.value
        console.log("添加了滚动事件");
        el.addEventListener("scroll",fn)
    })
    onUnmounted(() => {
        console.log("移除s了滚动事件");
        el.removeEventListener("scroll",fn)
    })


    return { scrollTop, clientHeight, scrollHeight, isBottom }
} 